package com.project.service.imp;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.project.bean.ClassBean;
import com.project.bean.StudentBean;
import com.project.mapper.IClassMapper;
import com.project.mapper.IStudentMapper;
import com.project.service.IClassService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class ClassService implements IClassService {

    @Autowired
    private IClassMapper classMapper;

    @Autowired
    private IStudentMapper studentMapper;
    @Override
    public List<ClassBean> findAllClass() {
        return classMapper.selectList(null);
    }

    @Override
    public boolean addClass(ClassBean classBean) {
        // 创建 QueryWrapper 对象，设置查询条件
        QueryWrapper<ClassBean> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("c_name", classBean.getName());
        // 查询符合条件的记录数量
        int count = classMapper.selectCount(queryWrapper);
        // 如果记录数量大于0，则说明班级名称已存在，直接返回 false
        if (count > 0) {
            return false;
        }
        // 否则，使用 classMapper.insert 方法将班级信息插入到数据库中，并返回 true
        classMapper.insert(classBean);
        return true;
    }

    @Override
    public boolean deleteClass(Integer classId) {
        // 按班级id统计学生人数
        QueryWrapper<StudentBean> qr = new QueryWrapper<>();
        qr.eq("fk_classId",classId);
        Integer count = studentMapper.selectCount(qr);
        // 如果班级的学生人数为0，则删除班级并返回true，否则返回false
        if (count == 0) {
            classMapper.deleteById(classId);
            return true;
        }
        return false;
    }
}
